package com.jintu.portal.service.impl;

import com.jintu.portal.pojo.bean.*;
import com.jintu.portal.pojo.dto.ArchitectureDataDto;
import com.jintu.portal.pojo.dto.DepartmentDto;
import com.jintu.portal.pojo.dto.UserDepartmentPostDto;
import com.jintu.portal.repository.mysql.dao.DepartmentDao;
import com.jintu.portal.repository.mysql.dao.UserDao;
import com.jintu.portal.repository.mysql.dao.UserDepartmentPostDao;
import com.jintu.portal.repository.mysql.dao.UserRoleDao;
import com.jintu.portal.service.UserService;
import com.jintu.portal.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by liyou on 2017/9/22.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserDepartmentPostDao userDepartmentPostDao;

//    @Autowired
//    private CompanyDao companyDao;
//
//    @Autowired
//    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

//    @Autowired
//    private PermissionDao permissionDao;
    @Autowired
    private DepartmentDao departmentDao;
//    @Autowired
//    private PostDao postDao;
//    @Autowired
//    private PostService postService;

//    @Transactional
//    public void register(RegisterDto registerDto) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("username", registerDto.getUsername()));
//        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("system", SystemType.OP_SYSTEM.getValue()));
//        TUser user = userDao.findOneByJpql(ql);
//        if(user != null) {
//            throw new ServiceException("该手机号已经在商家运营平台注册，不能重复注册");
//        }
//
//        TCompany company = new TCompany();
//        company.setCreateTime(new Date());
//        company.setIsUsed(IsUsed.USED.getValue());
//        company.setAddType(AddType.ADD.getValue());
//        company.setType(CooperatorType.SELF.getValue());
//        company.setUpdateTime(new Date());
//        companyDao.insert(company);
//
//        user = BeanUtils.copyProperties(registerDto, TUser.class);
//        user.setAddType(AddType.INIT.getValue());
//        user.setSystem(SystemType.OP_SYSTEM.getValue());
//        user.setLogicDelete(LogicDelete.NOT_DELETE.getValue());
//        Date now = new Date();
//        user.setCreateTime(now);
//        user.setUpdateTime(now);
//        user.setCompanyId(company.getId());
//        String password = StringUtil.toMD5(registerDto.getUsername()+registerDto.getPwd());
//        user.setPassword(password);
//        userDao.insert(user);
//
//        company.setCreator(user.getId());
//        company.setUpdater(user.getId());
//        companyDao.update(company);
//
//        TUserRole userRole = new TUserRole();
//        userRole.setRoleId(1L);
//        userRole.setUserId(user.getId());
//        userRoleDao.insert(userRole);
//    }
//    /**
//     * 岗位下对应的有效用户
//     * @param postId
//     * @return
//     * @throws Exception
//     */
//    public List<UserDepartmentPostDto> postUserList(Long postId) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.UserDepartmentPostDto(tp,tudp,tu) FROM TPost tp, TUserDepartmentPost tudp,TUser tu WHERE tp.id = tudp.postId and tudp.userId = tu.id");
//        ql.and(Filter.eq("tp.id", postId));
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        return userDepartmentPostDao.findManyByJpql(ql);
//    }
//
//    /**
//     * 部门下的所有有效员工,不包括子部门人员
//     * @param departmentId
//     * @return
//     * @throws Exception
//     */
//    public List<UserDepartmentPostDto> departmentUserList(Long departmentId) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.UserDepartmentPostDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id");
//        ql.and(Filter.eq("tdep.id", departmentId));
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        return userDepartmentPostDao.findManyByJpql(ql);
//    }
//
//    /**
//     * 根据筛选条件获得部门下的所有有效员工（包括子部门集合）
//     * @param userReqDto
//     * @return
//     * @throws Exception
//     */
//    public List<UserDepartmentPostDto> userList(UserReqDto userReqDto) throws Exception {
//        Integer status = userReqDto.getStatus();
//        if(status == null){
//            status = UserStatus.INCUMBENCY.getValue();
//        }
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.UserDepartmentPostDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id");
//        if(userReqDto.getDepartmentId() != null){
//            ql.and(Filter.eq("tdep.id", userReqDto.getDepartmentId()),Filter.eq("tdep.parentId", userReqDto.getDepartmentId()));
//        }
//        ql.and(Filter.eq("tu.status", status));
//        if(StringUtil.isNotEmpty(userReqDto.getKeyWord())){
//            ql.and(Filter.like("tu.username",userReqDto.getKeyWord()),Filter.like("tu.realname",userReqDto.getKeyWord()));
//        }
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        return userDepartmentPostDao.findManyByJpql(ql);
//    }
//
//    /**
//     * 根据用户ID获得用户详情(注意的是一个用户存在多个部门的情况)
//     * @param userId
//     * @return
//     * @throws Exception
//     */
//    public UserDepartmentPostDto userDetail(Long userId) throws Exception {
//        UserDepartmentPostDto departmentPostDto = null;
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.UserDepartmentPostDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id");
//        ql.and(Filter.eq("tu.id", userId));
//        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
//        List<UserDepartmentPostDto> userDepartmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
//        if(!CollectionUtils.isEmpty(userDepartmentPostDtoList)){
//            //基本信息只取第一个。
//            departmentPostDto = userDepartmentPostDtoList.get(0);
//            departmentPostDto.setDepartmentPostDtoList(userDepartmentPostDtoList);
//        }
//        return departmentPostDto;
//    }
//
//    /**
//     * 新增员工
//     * @param userReqDto
//     * @throws Exception
//     */
//    @Transactional
//    public void addEmployee(UserReqDto userReqDto) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("username", userReqDto.getPhoneNo()));
//        ql.and(Filter.eq("system", SystemType.B_APP_SYSTEM.getValue()));
//        //ql.and(Filter.eq("companyId", UserUtil.currentUser().getCompanyId()));
//        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        TUser user = userDao.findOneByJpql(ql);
//        if(user != null) {
//            throw new ServiceException("该手机号已经在商家运营平台注册，不能重复注册");
//        }
//        String defaultPwd = StringUtil.getRadomString(6, 0);
//        //新增员工
//        user = new TUser();
//        user.setUsername(userReqDto.getPhoneNo());
//        user.setRealname(userReqDto.getRealName());
//        user.setBirthday(userReqDto.getBirthdy());
//        user.setCreator(UserUtil.currentUser().getId());
//        user.setCreateTime(new Date());
//        user.setLogicDelete(LogicDelete.NOT_DELETE.getValue());
//        user.setStatus(UserStatus.INCUMBENCY.getValue());
//        user.setCompanyId(UserUtil.currentUser().getCompanyId());
//        user.setPassword(StringUtil.toMD5(userReqDto.getPhoneNo()+defaultPwd));
//        user.setSystem(SystemType.B_APP_SYSTEM.getValue());
//        user.setAddType(AddType.ADD.getValue());
//        //设置员工的退款权限
//        if(userReqDto.getRefundRight() != null && userReqDto.getRefundRight().intValue() == 1){
//            user.setRefundRight(1);
//        }else{
//            user.setRefundRight(null);
//        }
//        userDao.insert(user);
//        //TODO 需要发送短信通知 员工注册账号和密码
//        SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_ADD,userReqDto.getPhoneNo(),defaultPwd);
//
//        //新增部门岗位关联表信息
//        StringBuffer sb = new StringBuffer();
//        List<DepartmentPostDto> departmentPostDtoList = userReqDto.getDepartmentPostDtoList();
//        if(!CollectionUtils.isEmpty(departmentPostDtoList)){
//            TUserDepartmentPost userDepartmentPost = null;
//            for(DepartmentPostDto departmentPostDto : departmentPostDtoList){
//                TPost post = postDao.get(departmentPostDto.getPostId());
//                userDepartmentPost = new TUserDepartmentPost();
//                userDepartmentPost.setDepartmentId(departmentPostDto.getDepartmentId());
//                userDepartmentPost.setUserId(user.getId());
//                userDepartmentPost.setPostId(departmentPostDto.getPostId());
//                userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
//                userDepartmentPostDao.insert(userDepartmentPost);
//                //TODO 新增部门岗位，发送短信通知
//                SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_ADD_DEPARTMENT,departmentPostDto.getShortName(),post.getName());
//            }
//        }
//    }
//
//    /**
//     * 编辑员工
//     *  原部门和目标部门是否一致，{A不一致 新增关联表信息，停用原有员工部门。
//     *  B 一致 还需要看原岗位和目标岗位是否一致 （不一致 新增关联表信息，停用原有员工部门） 一致不需要处理}
//     *  0新增 1编辑岗位（停用原有岗位，新增新的岗位），2编辑（停用原有岗位，重新启用原停用岗位），3没做任何修改的
//     * @param userReqDto
//     * @throws Exception
//     */
//    @Transactional
//    public void updateEmployee(UserReqDto userReqDto) throws Exception {
//        //编辑员工
//        TUser user = userDao.get(userReqDto.getUserId());
//        user.setBirthday(userReqDto.getBirthdy());
//        user.setUpdater(UserUtil.currentUser().getId());
//        user.setUpdateTime(new Date());
//        //设置员工的退款权限
//        if(userReqDto.getRefundRight() != null && userReqDto.getRefundRight().intValue() == 1){
//            user.setRefundRight(1);
//        }else{
//            user.setRefundRight(null);
//        }
//        userDao.update(user);
//        //前台传入的部门信息
//
//        List<DepartmentPostDto> departmentPostDtoList = userReqDto.getDepartmentPostDtoList();
//        List<DepartmentPostDto> departmentPostDtoListNew = new ArrayList<DepartmentPostDto>();
//        if(!CollectionUtils.isEmpty(departmentPostDtoList)){
//            for(DepartmentPostDto dto : departmentPostDtoList){
//                if(dto.getChange() != null && IsUsed.USED.getValue() == dto.getChange()){
//                    //先停用系统原有可用的岗位
//                    TUserDepartmentPost stopUserDepartmentPost = userDepartmentPostDao.get(dto.getUserDepartmentId());
//                    stopUserDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
//                    userDepartmentPostDao.update(stopUserDepartmentPost);
//                    //拼接部门岗位信息用于短信通知
//                    TPost srcPost = postDao.get(stopUserDepartmentPost.getPostId());
//                    SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_STOP,dto.getShortName(),srcPost.getName());
//                    //TODO 将B端用户强制退出
//                    UserUtil.expireUserPost(stopUserDepartmentPost.getDepartmentId(),stopUserDepartmentPost.getPostId(),stopUserDepartmentPost.getUserId());
//                    continue;
//                }
//                departmentPostDtoListNew.add(dto);
//            }
//            Long targetDepartmentId = null;//目标部门ID
//            Long targetPostId = null;//目标部门ID
//            for(DepartmentPostDto departmentPostDto : departmentPostDtoListNew){
//                targetDepartmentId = departmentPostDto.getDepartmentId();
//                targetPostId = departmentPostDto.getPostId();
//                //根据用户部门岗位ID获得 中间表相关的对象
//                QLBuilder ql = new QLBuilder();
//                ql.and(Filter.eq("userId",userReqDto.getUserId()));
//                ql.and(Filter.eq("departmentId",departmentPostDto.getDepartmentId()));
//                ql.and(Filter.eq("postId",departmentPostDto.getPostId()));
//                TUserDepartmentPost srcUserDepartmentPost = userDepartmentPostDao.findOneByJpql(ql);
//                if(srcUserDepartmentPost != null){
//                    //编辑 停用启用岗位
//                    if(srcUserDepartmentPost.getIsUsed() == IsUsed.NOT_USED.getValue()){
//                        stopAndStartPost(userReqDto, targetPostId, departmentPostDto, srcUserDepartmentPost);
//                    }
//                }else{
//                    //查找部门下是否有可用岗位（新增或者（停用新增岗位））
//                    addOrStopPost(userReqDto, targetDepartmentId, targetPostId, departmentPostDto);
//                }
//            }
//        }
//    }
//
//    /**
//     * 新增岗位，和停用再新增岗位
//     * @param userReqDto
//     * @param targetDepartmentId
//     * @param targetPostId
//     * @param departmentPostDto
//     * @throws Exception
//     */
//    private void addOrStopPost(UserReqDto userReqDto, Long targetDepartmentId, Long targetPostId, DepartmentPostDto departmentPostDto) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("userId",userReqDto.getUserId()));
//        ql.and(Filter.eq("departmentId",departmentPostDto.getDepartmentId()));
//        ql.and(Filter.eq("isUsed", IsUsed.USED.getValue()));
//        TUserDepartmentPost src2UserDepartmentPost = userDepartmentPostDao.findOneByJpql(ql);
//        if(src2UserDepartmentPost != null){
//            //先停用系统原有可用的岗位，在新增
//            src2UserDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
//            userDepartmentPostDao.update(src2UserDepartmentPost);
//            //TODO 将B端用户强制退出
//            UserUtil.expireUserPost(src2UserDepartmentPost.getDepartmentId(),src2UserDepartmentPost.getPostId(),src2UserDepartmentPost.getUserId());
//            //拼接部门岗位信息用于短信通知
//            TPost srcPost = postDao.get(src2UserDepartmentPost.getPostId());
//            SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_STOP,departmentPostDto.getShortName(),srcPost.getName());
//
//        }
//        TUserDepartmentPost userDepartmentPostNew = new TUserDepartmentPost();
//        userDepartmentPostNew.setIsUsed(IsUsed.USED.getValue());
//        userDepartmentPostNew.setPostId(targetPostId);
//        userDepartmentPostNew.setDepartmentId(targetDepartmentId);
//        userDepartmentPostNew.setUserId(userReqDto.getUserId());
//        userDepartmentPostDao.insert(userDepartmentPostNew);
//        //拼接部门岗位信息用于短信通知
//        TPost targetPost = postDao.get(targetPostId);
//        //TODO 新增部门岗位，发送短信通知
//        SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_ADD_DEPARTMENT,departmentPostDto.getShortName(),targetPost.getName());
//    }
//
//    /**
//     * 停用和启用相关岗位
//     * @param userReqDto
//     * @param targetPostId
//     * @param departmentPostDto
//     * @param srcUserDepartmentPost
//     * @throws Exception
//     */
//    private void stopAndStartPost(UserReqDto userReqDto, Long targetPostId, DepartmentPostDto departmentPostDto, TUserDepartmentPost srcUserDepartmentPost) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("userId",userReqDto.getUserId()));
//        ql.and(Filter.eq("departmentId",departmentPostDto.getDepartmentId()));
//        ql.and(Filter.eq("isUsed", IsUsed.USED.getValue()));
//        TUserDepartmentPost src3UserDepartmentPost = userDepartmentPostDao.findOneByJpql(ql);
//        if(src3UserDepartmentPost != null){
//            //先停用系统原有可用的岗位，在新增
//            src3UserDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
//            userDepartmentPostDao.update(src3UserDepartmentPost);
//            //拼接部门岗位信息用于短信通知
//            TPost srcPost = postDao.get(src3UserDepartmentPost.getPostId());
//            SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_STOP,departmentPostDto.getShortName(),srcPost.getName());
//            //TODO 将B端用户强制退出
//            UserUtil.expireUserPost(src3UserDepartmentPost.getDepartmentId(),src3UserDepartmentPost.getPostId(),src3UserDepartmentPost.getUserId());
//        }
//        //启用 系统原有部门
//        srcUserDepartmentPost.setIsUsed(IsUsed.USED.getValue());
//        userDepartmentPostDao.update(srcUserDepartmentPost);
//        //拼接部门岗位信息用于短信通知
//        TPost targetPost = postDao.get(targetPostId);
//        SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_START,departmentPostDto.getShortName(),targetPost.getName());
//    }
//
//    /**
//     * 当前用户对应的所有部门岗位信息
//     * @param userId
//     * @return
//     */
//    private List<TUserDepartmentPost> userDpListByuserId(Long userId){
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("userId",userId));
//        List<TUserDepartmentPost> userDepartmentPostList = userDepartmentPostDao.findManyByJpql(ql);
//        return userDepartmentPostList;
//    }
//
//    /**
//     * 封装用户部门岗位对象通过userID
//     * @return
//     * @throws Exception
//     */
//    public Map<Long, TUserDepartmentPost> userDepartmentPostByDPId(Long userId) throws Exception {
//        Map<Long,TUserDepartmentPost> userDepartmentPostMap = new HashMap<Long, TUserDepartmentPost>();
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
//        ql.and(Filter.eq("userId",userId));
//        List<TUserDepartmentPost> userDepartmentPostList = userDepartmentPostDao.findManyByJpql(ql);
//        if(!CollectionUtils.isEmpty(userDepartmentPostList)){
//            for(TUserDepartmentPost userDepartmentPost : userDepartmentPostList){
//                userDepartmentPostMap.put(userDepartmentPost.getId(),userDepartmentPost);
//            }
//        }
//        return userDepartmentPostMap;
//    }
//
//    /**
//     * 用户操作类型 1停用，2启用，3通过，4拒绝，5离职
//     * @param userDepartmentPostDto
//     * @param operType
//     * @throws Exception
//     */
//    @Transactional
//    public void userOper(UserDepartmentPostDto userDepartmentPostDto,Integer operType) throws Exception {
//        TUserDepartmentPost userDepartmentPost = null;
//        List<UserDepartmentPostDto> userDepartmentPostDtoList = null;
//        if(operType == UserOperType.STOPOPER.getValue()){
//            userDepartmentPost = userDepartmentPostDao.get(userDepartmentPostDto.getUserDepartmentId());
//            userDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
//            userDepartmentPostDao.update(userDepartmentPost);
//            //发送短信信息
//            SmsUtil.send(userDepartmentPostDto.getUserName(), MsgType.USER_STOP,userDepartmentPostDto.getShortName(),userDepartmentPostDto.getPostName());
//            //TODO 将B端用户强制退出
//            UserUtil.expireUserPost(userDepartmentPost.getDepartmentId(),userDepartmentPost.getPostId(),userDepartmentPost.getUserId());
//        }else if(operType == UserOperType.STARTOPER.getValue()){
//            QLBuilder ql = new QLBuilder();
//            ql.and(Filter.eq("userId",userDepartmentPostDto.getUserId()));
//            ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
//            ql.and(Filter.eq("departmentId",userDepartmentPostDto.getDepartmentId()));
//            userDepartmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
//            if(!CollectionUtils.isEmpty(userDepartmentPostDtoList)){
//                throw new ServiceException("当前员工（"+userDepartmentPostDto.getRealName()+"）已经在（"+userDepartmentPostDto.getShortName()+"）拥有其他岗位，无法恢复当前职位！");
//            }else{
//                userDepartmentPost = userDepartmentPostDao.get(userDepartmentPostDto.getUserDepartmentId());
//                userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
//                userDepartmentPostDao.update(userDepartmentPost);
//                //发送短信信息
//                SmsUtil.send(userDepartmentPostDto.getUserName(), MsgType.USER_START,userDepartmentPostDto.getShortName(),userDepartmentPostDto.getPostName());
//            }
//        }else if(operType == UserOperType.PASSOPER.getValue()){
//            TUser user = userDao.get(userDepartmentPostDto.getUserId());
//            user.setStatus(UserStatus.INCUMBENCY.getValue());
//            user.setUpdateTime(new Date());
//            user.setUpdater(UserUtil.currentUser().getId());
//            user.setAuditor(UserUtil.currentUser().getId());
//            user.setAuditTime(new Date());
//            userDao.update(user);
//            //更新对应部门可用
//            userDepartmentPost = userDepartmentPostDao.get(userDepartmentPostDto.getUserDepartmentId());
//            userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
//            userDepartmentPostDao.update(userDepartmentPost);
//            //发送短信信息
//            SmsUtil.send(userDepartmentPostDto.getUserName(), MsgType.USER_CHECK_SUCC,userDepartmentPostDto.getUserName());
//        }else if(operType == UserOperType.REFUSEOPER.getValue()){
//            TUser user = userDao.get(userDepartmentPostDto.getUserId());
//            user.setLogicDelete(LogicDelete.DELETE.getValue());
//            user.setUpdateTime(new Date());
//            user.setUpdater(UserUtil.currentUser().getId());
//            user.setAuditor(UserUtil.currentUser().getId());
//            user.setAuditTime(new Date());
//            userDao.update(user);
//            // 发送短信信息
//            SmsUtil.send(userDepartmentPostDto.getUserName(), MsgType.USER_REFUED);
//        }else if(operType == UserOperType.DIMISSIONOPER.getValue()){
//            QLBuilder ql = new QLBuilder();
//            ql.and(Filter.eq("userId",userDepartmentPostDto.getUserId()));
//            ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
//            userDepartmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
//            if(!CollectionUtils.isEmpty(userDepartmentPostDtoList)){
//                throw new ServiceException("当前员工（"+userDepartmentPostDto.getRealName()+"）还有其他正常使用的职位，暂时无法离职");
//            }else{
//                TUser user = userDao.get(userDepartmentPostDto.getUserId());
//                user.setLogicDelete(LogicDelete.DELETE.getValue());
//                user.setUpdateTime(new Date());
//                user.setUpdater(UserUtil.currentUser().getId());
//                userDao.update(user);
//            }
//        }
//    }
//
//
//    /**
//     * 根据筛选条件获得部门下的所有有效员工(分页)
//     * @param userReqDto
//     * @return
//     * @throws Exception
//     */
//    public Pagination userPageList(UserReqDto userReqDto) throws Exception {
//        Pageable pageable = new Pageable();
//        pageable.setPageNumber(userReqDto.getPageNo());
//        Integer status = userReqDto.getStatus();
//        if(status == null){
//            status = UserStatus.INCUMBENCY.getValue();
//        }
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.UserDepartmentPostDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId=tu.companyId");
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tdep.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tu.companyId", UserUtil.currentUser().getCompanyId()));
//        if(userReqDto.getDepartmentId() != null){
//            TDepartment department = departmentDao.get(userReqDto.getDepartmentId());
//            ql.and(Filter.like("tdep.fullPath",department.getFullPath()+"%"));
//            //ql.and(Filter.eq("tdep.id", userReqDto.getDepartmentId()),Filter.eq("tdep.parentId",userReqDto.getDepartmentId()));
//        }
//        if(status == UserStatus.PENDING.getValue()){
//            ql.and(Filter.eq("tu.status", UserStatus.PENDING.getValue()));
//            ql.and(Filter.eq("tudp.isUsed",IsUsed.NOT_USED.getValue()));
//        }else if(status == UserStatus.INCUMBENCY.getValue()){
//            ql.and(Filter.eq("tu.status",  UserStatus.INCUMBENCY.getValue()));
//            ql.and(Filter.eq("tudp.isUsed",IsUsed.USED.getValue()));
//        }else{
//            ql.and(Filter.eq("tu.status",  UserStatus.INCUMBENCY.getValue()));
//            ql.and(Filter.eq("tudp.isUsed",IsUsed.NOT_USED.getValue()));
//        }
//
//        if(StringUtil.isNotEmpty(userReqDto.getKeyWord())){
//            ql.and(Filter.like("tu.username","%"+userReqDto.getKeyWord()+"%"),Filter.like("tu.realname","%"+userReqDto.getKeyWord()+"%"));
//        }
//        ql.add(" order by tu.createTime desc,tudp.id desc");
//        Pagination pagination = userDepartmentPostDao.findPageByJpql(ql, pageable);
//        return pagination;
//    }
//
//    /**
//     * 员工管理下根据条件筛选相关员工(导出)
//     * @param userReqDto
//     * @return
//     * @throws Exception
//     */
//    public List<UserDepartmentPostDto> userPageListExcel(UserReqDto userReqDto) throws Exception{
//        StringBuffer sb = new StringBuffer();
//        List<Object> paramList = new ArrayList<Object>();
//        String sql ="select tu.realname realName,tu.username userName,tp.`name` postName,tp.type,tdep.short_name shortName,tu.`status`,tudp.is_used isUsed "+
//                    "FROM t_user_department_post tudp,t_department tdep,t_post tp,t_user tu "+
//                    "where tudp.department_id = tdep.id and tudp.post_id=tp.id and tudp.user_id = tu.id and tdep.company_id=tu.company_id ";
//        sb.append(sql);
//        sb.append(" and tu.logic_delete= :logicDelete");
//        paramList.add(LogicDelete.NOT_DELETE.getValue());
//        sb.append(" and tdep.logic_delete= :logicDelete");
//        paramList.add(LogicDelete.NOT_DELETE.getValue());
//        sb.append(" and tu.company_id= :companyId");
//        paramList.add(UserUtil.currentUser().getCompanyId());
//        if(userReqDto.getDepartmentId() != null){
//            TDepartment department = departmentDao.get(userReqDto.getDepartmentId());
//            sb.append(" and tdep.full_path like :fullPath");
//            paramList.add(department.getFullPath()+"%");
//        }
//        Integer status = userReqDto.getStatus();
//        if(status == null){
//            status = UserStatus.INCUMBENCY.getValue();
//        }
//        if(status == UserStatus.PENDING.getValue()){
//            sb.append(" and tu.status= :status");
//            paramList.add(UserStatus.PENDING.getValue());
//            sb.append(" and tudp.is_used= :isUsed");
//            paramList.add(IsUsed.NOT_USED.getValue());
//        }else if(status == UserStatus.INCUMBENCY.getValue()){
//            sb.append(" and tu.status= :status");
//            paramList.add(UserStatus.INCUMBENCY.getValue());
//            sb.append(" and tudp.is_used= :isUsed");
//            paramList.add(IsUsed.USED.getValue());
//        }else{
//            sb.append(" and tu.status= :status");
//            paramList.add(UserStatus.INCUMBENCY.getValue());
//            sb.append(" and tudp.is_used= :isUsed");
//            paramList.add(IsUsed.NOT_USED.getValue());
//        }
//        if(StringUtil.isNotEmpty(userReqDto.getKeyWord())){
//            sb.append(" and (tu.username like :userName or tu.realname like :relName) ");
//            paramList.add("%"+userReqDto.getKeyWord()+"%");
//            paramList.add("%"+userReqDto.getKeyWord()+"%");
//        }
//        sb.append(" order by tu.create_time desc,tudp.id desc");
//        List<UserDepartmentPostDto> pagination =  userDepartmentPostDao.findManyBySql(sb.toString(), UserDepartmentPostDto.class, paramList.toArray());
//        return pagination;
//    }
//
//    /**
//     * 验证用户操作员工管理信息
//     * @param userDepartmentPostDto
//     * @param operType
//     * @return
//     * @throws Exception
//     */
//    public void validUserOper(UserDepartmentPostDto userDepartmentPostDto, Integer operType) throws Exception {
//        List<UserDepartmentPostDto> userDepartmentPostDtoList = null;
//        if(operType == UserOperType.DIMISSIONOPER.getValue()){
//            QLBuilder ql = new QLBuilder();
//            ql.and(Filter.eq("userId",userDepartmentPostDto.getUserId()));
//            ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
//            userDepartmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
//            if(!CollectionUtils.isEmpty(userDepartmentPostDtoList)){
//                throw new ServiceException("当前员工（"+userDepartmentPostDto.getRealName()+"）还有其他正常使用的职位，暂时无法离职");
//            }else{
//                throw new ServiceException(200, "当前员工（"+userDepartmentPostDto.getRealName()+"）所有工作已完成交接，确定离职？");
//            }
//        }
//    }

    /**
     * 首页数据架构，门店集合和员工集合
     * @return
     * @throws Exception
     */
    public ArchitectureDataDto architectureData() throws Exception {
        ArchitectureDataDto dataDto = new ArchitectureDataDto();
        Integer storeCount = 0;
        Integer employeeCount = 0;
        QLBuilder ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.DepartmentDto(tdep) FROM TDepartment tdep");
        ql.and(Filter.eq("tdep.companyId", UserUtil.currentUser().getCompanyId()));
        ql.and(Filter.eq("tdep.isStore", IsStore.STORE.getValue()));
        ql.and(Filter.eq("tdep.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        List<DepartmentDto> departmentDtoList =  departmentDao.findManyByJpql(ql);
        if(!CollectionUtils.isEmpty(departmentDtoList)){
            storeCount = departmentDtoList.size();
        }
        dataDto.setStoreCount(storeCount);

        //公司下的员工数量
        List<Object> paramList = new ArrayList<Object>();
        String sql="SELECT DISTINCT(tudp.user_id) userId FROM t_user_department_post tudp, t_department tdep, t_post tp,t_user tu WHERE tudp.department_id = tdep.id and tudp.post_id=tp.id and tudp.user_id = tu.id and tdep.company_id=tu.company_id and tu.logic_delete ="+LogicDelete.NOT_DELETE.getValue()+" and tu.status="+ UserStatus.INCUMBENCY.getValue()+" and tu.company_id = :companyId";
        paramList.add(UserUtil.currentUser().getCompanyId());
        List<UserDepartmentPostDto> employeeList = userDepartmentPostDao.findManyBySql(sql,UserDepartmentPostDto.class,paramList.toArray());
        if(!CollectionUtils.isEmpty(employeeList)){
            employeeCount = employeeList.size();
        }
        dataDto.setEmployeeCount(employeeCount);
        return dataDto;
    }

//    public TUser getInitAdminUser(Long companyId) {
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("companyId", companyId));
//        ql.and(Filter.eq("system", SystemType.OP_SYSTEM.getValue()));
//        ql.and(Filter.eq("addType", AddType.INIT.getValue()));
//        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        return userDao.findOneByJpql(ql);
//    }
//
//    /**
//     * 用户对应的部门岗位信息
//     * @param userReqDto
//     * @return
//     * @throws Exception
//     */
//    public List<DepartmentPostDto> userDepPostList(UserReqDto userReqDto) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.org.dto.user.DepartmentPostDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId=tu.companyId");
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
//        ql.and(Filter.eq("tu.companyId", UserUtil.currentUser().getCompanyId()));
//        ql.and(Filter.eq("tu.id", userReqDto.getUserId()));
//        List<DepartmentPostDto> departmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
//        //TODO 后续需要优化
//        List<PostDto> postList = null;
//        for(DepartmentPostDto departmentPostDto : departmentPostDtoList){
//            postList = new ArrayList<PostDto>();
//            List<PostDto> postDtoList = postService.postDtoDepartmentTypeList(departmentPostDto.getDepartmentTypeId());
//            for(PostDto postDto : postDtoList){
//                postList.add(postDto);
//            }
//            departmentPostDto.setPostList(postList);
//        }
//        return departmentPostDtoList;
//    }

}
